package com.daybreak.component_security;

import com.alibaba.fastjson.JSONObject;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 无权限访问被拒绝时的自定义处理器。如不自己处理，默认返回403错误
 */
@Component
public class MyAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
        JSONObject params = new JSONObject();
        params.put("code", 403);
        params.put("msg", "您无此资源的访问权限！");
        response.sendRedirect("noRole.html");
        /*//设置返回请求头
        response.setContentType("application/json;charset=utf-8");
        //写出流
        PrintWriter out = response.getWriter();
        out.write(params.toJSONString());
        out.flush();
        out.close();*/
    }
}
